package mtn.lgdx.GPS;

import android.app.*;
import android.content.*;
import android.location.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.net.*;
import android.net.*;

import com.baidu.location.*;


public class MainActivity extends Activity {
	private boolean swFlag; //显示结果开关
	private long current; //当前时间，用于返回键退出
	private final int DELAY = 20000; //坐标更新周期20s
	private final int ERROR_DELAY = 1000;
	private double radius = 0; //精度范围
	private String description = "";
	boolean tip = true; //到位提示
	private Coord coord_start = null, coord_end = null;
	private LocationClient mLocationClient = null;
	private final BDLocationListener myListener = new MyLocationListener();
	private final ButtonListener buttonListener = new ButtonListener();
	
	private TableRow tr3;
	private TextView info, tv1, tv2, tv3, tv4;
	private EditText et1, et2;
	private Button btn2, btn3, sw;
	private Toast toast = null;
	private AlertDialog alertDialog1 = null, alertDialog2 = null;
	private Vibrator vibrator = null;

	
	/**Button listener**/
	private final class ButtonListener implements View.OnClickListener {
		@Override
		public void onClick(View p) {
			switch (p.getId()) {
				case R.id.mainButton2:
/*在地图上标定天安门*/
//Uri uri = Uri.parse("geo:"+39.9+","+116.4);
					try {
						Intent intent;
						if (swFlag) {
							intent = Intent.getIntent("intent://map/marker?location=" + coord_start.getRawLat() + "," + coord_start.getRawLon() + "&title=站立点&content=("+coord_start.getX()+","+coord_start.getY()+")&coord_type=gcj02&src=Plaust|高斯地形学#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
						}
						else {
							intent = Intent.getIntent("intent://map/direction?origin=latlng:"+coord_start.getRawLat()+","+coord_start.getRawLon()+"|name:起点&destination=latlng:"+coord_end.getRawLat()+","+coord_end.getRawLon()+"|name:终点&mode=walking&region=&coord_type=gcj02&src=#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
						}
						startActivity(intent);
					}
					catch (URISyntaxException e) {
						android.util.Log.e("SYNC_ERROR", e.getMessage());
					}
					break;
				case R.id.mainButton3:
					/*update position manually*/
					toast.setText(R.string.position_updating);
					toast.show();
					if (mLocationClient != null && mLocationClient.isStarted()) 
						mLocationClient.requestLocation();
					break;
				case R.id.switchButton:
					if (swFlag == true) {
						if (et1.getText().toString().length() == 7 && et2.getText().toString().length() == 8) { //检查长度
							et1.setEnabled(false);
							et2.setEnabled(false);
							sw.setText(R.string.clear);
							swFlag = !swFlag;
							tr3.setVisibility(View.VISIBLE);
							coord_end.setX(Integer.parseInt(et1.getText().toString())).setY(Integer.parseInt(et2.getText().toString())).gauss2Geo();
							Coord.anticalc(coord_start, coord_end);
							showResult();
						}
						else {
							toast.setText(R.string.input_check);
							toast.show();
						}
					}
					else {
						et1.setText("");
						et1.setEnabled(true);
						tr3.setFocusableInTouchMode(true);
						tr3.requestFocus();
						et2.setText("");
						et2.setEnabled(true);
						sw.setText(R.string.done);
						swFlag = !swFlag;
						tr3.setVisibility(View.GONE);
						tip = true;
					}
					break;
			}
		}
	}
	


	/**Position listener**/
	public class MyLocationListener implements BDLocationListener { 
		@Override 
		public void onReceiveLocation(BDLocation location) {
			int _locType = location.getLocType();
			android.util.Log.i("ERROR_CODE", String.valueOf(_locType));
			if (!Utils.isOnline(MainActivity.this) || (_locType != BDLocation.TypeGpsLocation && _locType != BDLocation.TypeNetWorkLocation && _locType != BDLocation.TypeOffLineLocation)) {
				alertDialog1.show();
				vibrator.vibrate(ERROR_DELAY);
				return;
			}
			description = "";
			if ( location.hasRadius()) {
				radius = location.getRadius();
				description += "精度" + String.format("%1.1f", radius) + "m\n";
			}
			if (location.hasAltitude()) {
				description += "海拔" + String.format("%1.1f", location.getAltitude()) + "m\n";
				description += "方向" + location.getDirection() + "度\n";
			}
			if (location.hasSpeed()) {
				description += "速度" + String.format("%1.1f", location.getSpeed()) + "m/s\n";
			}
			if (location.hasSateNumber()) {
				description += "星数" + String.format("%d", location.getSatelliteNumber());
			}
			//if (location.getLocationDescribe())
			coord_start.setCoord(location.getLatitude(), location.getLongitude());
//coord_start.setLat(41.81442).setLon(81.82382);		
			coord_start.geo2Gauss();
//		Toast.makeText(MainActivity.this, "Location-Lat:"+location.getLatitude()+" Lon:"+location.getLongitude()
//		+ "\nassign-Lat:" + coord_start.getLat()+" Lon:"+coord_start.getLon()
//		+ "\nend-Lat:" + coord_end.getRawLat() + " Lon:" + coord_end.getRawLon(), Toast.LENGTH_LONG).show();
//		android.util.Log.d("Location", "Lan:"+location.getLatitude()+"Lon:"+location.getLongitude());
//		android.util.Log.d("assign", "Lan:"+coord_start.getLat()+"Lon:"+coord_start.getLon());
			show();
		}
	}


	/**两次返回键退出**/
	@Override
	public void onBackPressed() {
		if (System.currentTimeMillis() - current > 2000) {
			current = System.currentTimeMillis();
			Toast.makeText(this, R.string.double_back_to_exit, Toast.LENGTH_SHORT).show();
		}
		else {
			android.os.Process.killProcess(android.os.Process.myPid());
			finish();
		}
	}


	/**first launch**/
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		coord_start = new Coord();
		coord_end = new Coord();
		setTheme(Utils.getTheme());
		setContentView(R.layout.main);
		tr3 = (TableRow)findViewById(R.id.mainTableRow3);
		info = (TextView)findViewById(R.id.info);
		tv1 = (TextView)findViewById(R.id.mainTextView1);
		tv2 = (TextView)findViewById(R.id.mainTextView2);
		tv3 = (TextView)findViewById(R.id.mainTextView3);
		tv4 = (TextView)findViewById(R.id.mainTextView4);
		et1 = (EditText)findViewById(R.id.mainEditText1);
		et2 = (EditText)findViewById(R.id.mainEditText2);
		btn2 = (Button)findViewById(R.id.mainButton2);
		btn3 = (Button)findViewById(R.id.mainButton3);
		sw = (Button)findViewById(R.id.switchButton);
		et2.setNextFocusDownId(sw.getId());
		et2.setNextFocusForwardId(sw.getId());
		btn2.setOnClickListener(buttonListener);
		btn3.setOnClickListener(buttonListener);
		sw.setOnClickListener(buttonListener);
		toast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
		alertDialog1 = new AlertDialog.Builder(MainActivity.this).setTitle(R.string.error).setMessage(R.string.please_check).setNeutralButton(R.string.done, 
			new DialogInterface.OnClickListener() { 
				@Override public void onClick(DialogInterface dialog, int which) { 
//					try {
//						Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
//						MainActivity.this.startActivity(intent);
//					}
//					catch (Exception ex) {
//						android.util.Log.i("NETWORK", "open network settings failed");
//					}
				}
			}).create();
		alertDialog2 = new AlertDialog.Builder(MainActivity.this).setTitle("").setMessage(R.string.arrived).setNeutralButton(R.string.done, 
			new DialogInterface.OnClickListener() { 
				@Override public void onClick(DialogInterface dialog, int which) { 

				}
			}).create();
		vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);
		swFlag = true; //标记确认状态
		current = 0;
//		if (!isOnline()) {
//			alertDialog1.show();
//			vibrator.vibrate(ERROR_DELAY);
//		}

		Toast.makeText(MainActivity.this, R.string.tips, Toast.LENGTH_SHORT).show();
		mLocationClient = new LocationClient(getApplicationContext()); //声明Location Client类
		LocationClientOption option = new LocationClientOption();
		option.setProdName("高斯地形学"); //设置产品线名称
		option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//设置定位模式
		option.setCoorType("gcj02"); //国测局坐标系
		option.setOpenGps(true);
		option.setLocationNotify(false);//可选，默认false，设置是否当gps有效时按照1S1次频率 输出GPS结果
		option.setScanSpan(DELAY);//设置发起定位请求的间隔时间为DELAYms
		mLocationClient.setLocOption(option);
		mLocationClient.registerLocationListener(myListener); //注册监听函数
	}


	/**选项菜单**/
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.FIRST, Menu.FIRST, Menu.FIRST, R.string.about).setIcon(android.R.drawable.ic_dialog_info);
		menu.add(Menu.FIRST + 1, Menu.FIRST + 1, Menu.FIRST + 1, Utils.getMenuTitle1()).setIcon(android.R.drawable.ic_menu_edit);
		menu.add(Menu.FIRST + 2, Menu.FIRST + 2, Menu.FIRST + 2, R.string.exit).setIcon(android.R.drawable.ic_lock_power_off);
		return super.onCreateOptionsMenu(menu);
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		mLocationClient.unRegisterLocationListener(myListener);	
	}


	/*设置菜单功能*/
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case Menu.FIRST:
				/*关于界面*/
				startActivity(new Intent(MainActivity.this, AboutActivity.class));
				break;
			case Menu.FIRST + 1:
				Utils.changeTheme(this);
				break;
			case Menu.FIRST + 2:
				android.os.Process.killProcess(android.os.Process.myPid());
				finish();
				break;
		}
		return super.onOptionsItemSelected(item);
	}


	@Override
	protected void onPause() {
		super.onPause();
		mLocationClient.stop();
	}


	@Override
	protected void onResume() {
		super.onResume();
		mLocationClient.start();
	}


	/**show position**/
	private void show() {
//geo2Gauss(39.90960456,116.39722824); //(4419744,20448458) expect in Beijing54 and (4419668,20448459) in Xian80
//coord_start.setLat(39.90960456).setLon(116.39722824).geo2Gauss();
		info.setText(description);
		tv1.setText(String.format("%05d", coord_start.getX()));
		tv2.setText(String.format("%05d", coord_start.getY()));
//		toast.setText(R.string.position_updated);
//		toast.show();
		if (swFlag == false) { //确保现地坐标和目标点坐标有值
			Coord.anticalc(coord_start, coord_end);
//	Toast.makeText(this,"Alfa:"+coord_start.getAlfa()+"\nD:"+coord_start.getDistance(),Toast.LENGTH_LONG).show();
			showResult();
		}
	}


	/**show alfa and distance**/
	private void showResult() {
//Toast.makeText(this,"coord_end:N"+coord_end.getLat()+",E"+coord_end.getLon(),Toast.LENGTH_LONG).show();
		int _alfa = Coord.toMil(coord_start.getAlfa());
		String _sAlfa = "" + _alfa / 100 + "-" + String.format("%02d", _alfa % 100);
		tv3.setText(_sAlfa);
		tv4.setText(String.valueOf(Math.round(coord_start.getDistance())));	
		if (tip && coord_start.getDistance() < radius) {
			//最好2次振动，像消息提醒
			vibrator.vibrate(500);
			tip = false;
			alertDialog2.show();
		}
	}
	
}
